package com.zhang.mysql;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 深圳金雅福控股集团有限公司
 *
 * @author zhangfanjun
 * @date 2022/4/22
 */
public class DBContextHolder {

    private static final Logger log = LoggerFactory.getLogger(DBContextHolder.class);
    private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal();
    private static final AtomicInteger counter = new AtomicInteger(-1);

    public DBContextHolder() {
    }

    public static void set(DBTypeEnum dbType) {
        contextHolder.set(dbType);
    }

    public static DBTypeEnum get() {
        return (DBTypeEnum)contextHolder.get();
    }

    public static void master() {
        log.info("mybatis datasource change to {}", DBTypeEnum.MASTER);
        set(DBTypeEnum.MASTER);
    }

    public static void slave() {
        int index = counter.getAndIncrement() % 2;
        if (counter.get() > 9999) {
            counter.set(-1);
        }

        if (index == 0) {
            log.info("mybatis datasource change to {}", DBTypeEnum.SLAVE1);
            set(DBTypeEnum.SLAVE1);
        } else {
            log.info("mybatis datasource change to {}", DBTypeEnum.SLAVE2);
            set(DBTypeEnum.SLAVE2);
        }

    }
}